package com.zj.leetcode.easy.tree;

/**
 * @program: algorithm
 * @description: 二叉树的坡度
 * 563 binary-tree-tilt
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class BinaryTreeTilt {
    public static void main(String[] args) {
        Solution solution = new BinaryTreeTilt().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        private int result;

        public int findTilt(TreeNode root) {
            this.result = 0;
            dfs(root);
            return this.result;
        }

        private int dfs(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int left = dfs(root.left);
            int right = dfs(root.right);
            this.result += Math.abs(left - right);
            return left + right + root.val;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
